package com.xiaoyung.easyisapisdk.common.util;

import java.lang.reflect.Type;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

import feign.RequestTemplate;
import feign.codec.EncodeException;
import feign.codec.Encoder;

public class ObjectEncoder implements  Encoder {
	private static Logger logger = LoggerFactory.getLogger(ObjectEncoder.class);

	public ObjectEncoder(){
		
	}
	@Override
	public void encode(Object object, Type bodyType, RequestTemplate template) throws EncodeException {
		if (object == null)
			return;
		
		String body = null;
		boolean isStringBody = true;
		if (bodyType == String.class || object instanceof String ) {
			//debug(object.toString());
			//template.body(object.toString());
			body= object.toString();
			//logger.debug("String类型");
		}else if(bodyType == JSONObject.class || bodyType == JSONArray.class) {
			body = JSONUtils.objectToJsonString(object);
			//body=((JSON)object).toString(SerializerFeature.WriteMapNullValue,SerializerFeature.WriteDateUseDateFormat);
			//debug(body);
			//template.body(body);
			//logger.debug("JSONOBject|JSONArray类型");
		} else if (bodyType == byte[].class) {
			template.body((byte[]) object, null);
			//logger.debug("byte[]类型");
			isStringBody = false;
		} else  {
			//logger.debug("默认转jsonString ");
			body = JSONUtils.objectToJsonString(object);
			//body = JSON.toJSONString(object,SerializerFeature.WriteMapNullValue,SerializerFeature.WriteDateUseDateFormat);
			//debug(body);
		}
		if(isStringBody) {
			template.body(body);
			logger.debug("request body: "+body);
		}else {
			logger.debug("request body 是字节数组 ");
		}
		
		/*else {
			throw new EncodeException(format("%s is not a type supported by this encoder.", object == null ? null : object.getClass()));
		}*/
		
	}
	
	/*private void debug(String body) {
		System.out.println(body);
	}*/
	
}
